<template>
    <view>
        <!-- 顶部标题 -->
        <!-- <view class="cu-custom" :style="[{height:CustomBar + 'px'}]">
            <view class="cu-bar fixed gold-bg" :style="[{height:CustomBar + 'px',paddingTop:StatusBar + 'px'}]">
                <view class="content text-bold">BSA检测预约</view>
            </view>
        </view> -->
        <cu-custom :bgImage="bgImage">
            <view class="text-bold text-black" slot="content">BSA检测预约</view>
        </cu-custom>
        
        <!-- 选择检测中心 -->
        <view class="padding-sm padding-tb-xs">
            <view class="padding-lr bg-white radius">
                <picker @change="centerChange" :value="centerIndex" :range="centers" range-key="name">
                    <view class="picker padding-tb flex justify-between align-center">
                        <text>{{centers[centerIndex].name}}</text>
                        <text class="cuIcon-unfold text-gray"></text>
                    </view>
                </picker>
            </view>
        </view>
        
        <!-- 日期选择 -->
        <view class="padding-sm padding-tb-xs">
            <scroll-view class="bg-white padding-xs" scroll-x>
                <view class="date-scroll-container">
                    <view class="date-item" v-for="(date, index) in dateList" :key="index" 
                          :class="selectedDate === index ? 'selected' : ''" @tap="selectDate(index)">
                        <view class="text-center">{{date.day}}</view>
                        <view class="text-center text-sm">{{date.week}}</view>
                    </view>
                </view>
            </scroll-view>
        </view>
        
        <!-- 时间选择 -->
        <view class="padding-sm padding-tb-xs">
            <view class="bg-white padding radius">
                <view class="grid col-3 gap-3">
                    <view class="time-item" v-for="(time, index) in timeList" :key="index"
                          :class="{'disabled': time.status === '已约满', 'selected': selectedTime === index}"
                          @tap="selectTime(index, time)">
                        <view class="text-center">{{time.time}}</view>
                        <view class="text-center text-sm" :class="time.status === '已约满' ? 'text-red' : 'text-green'">
                            {{time.status}}
                        </view>
                    </view>
                </view>
            </view>
        </view>
        
        <!-- 选择检测师 -->
        <view class="padding-sm padding-tb-xs">
            <view class="bg-white padding radius">
                <view class="text-bold margin-bottom-sm">选择检测师</view>
                <view class="tester-scroll-container" ref="scrollContainer">
                    <scroll-view class="tester-scroll" scroll-x ref="testerScroll" @scroll="onTesterScroll">
                        <view class="tester-container" ref="testerContainer">
                            <view class="tester-item" v-for="(tester, index) in testers" :key="index"
                                  :class="selectedTester === index ? 'selected' : ''" @tap="selectTester(index)">
                                <image class="tester-avatar" :src="tester.avatar || avatar" mode="aspectFill"></image>
                                <view class="text-center text-sm">{{tester.name}}</view>
                            </view>
                        </view>
                    </scroll-view>
                    <!-- 右侧滑动指示箭头 -->
                    <view class="tester-scroll-indicator" v-if="showScrollIndicator">
                        <text class="cuIcon-right"></text>
                    </view>
                </view>
            </view>
        </view>
        
        <!-- 确认按钮 -->
        <view class="padding">
            <button class="cu-btn block bg-gold xs" @tap="confirmAppointment">请选择时间和检测师</button>
        </view>
        
        <!-- 我的预约列表 -->
        <view class="padding-sm">
            <view class="bg-white padding radius">
                <view class="text-bold">我的客户预约列表</view>
                
                <!-- 列表切换tabs -->
                <view class="appointment-tabs">
                    <view class="appointment-tab-item" :class="appointmentTab === 0 ? 'active' : ''" @tap="appointmentTab = 0">
                        已预约
                        <view class="tab-line" v-if="appointmentTab === 0"></view>
                    </view>
                    <view class="appointment-tab-item" :class="appointmentTab === 1 ? 'active' : ''" @tap="appointmentTab = 1">
                        已检测
                        <view class="tab-line" v-if="appointmentTab === 1"></view>
                    </view>
                </view>
                
                <!-- 预约列表 -->
                <view class="appointment-list" v-if="appointmentTab === 0">
                    <view class="appointment-item" v-for="(item, index) in myAppointments" :key="index">
                        <view class="flex align-center">
                            <view class="appointment-avatar">
                                <image class="appointment-avatar-image" :src="item.avatar"></image>
                                <view style="font-size: 24rpx;text-align: center;">{{item.name}}</view>
                            </view>
                            
                            <view class="margin-left-sm flex-1">
                                <view class="text-gray text-sm">预约时间：{{item.time}}</view>
                                <view class="text-gray text-sm">预约地点：{{item.center}}</view>
                                <view class="text-gray text-sm">检测师：{{item.tester}}</view>
                            </view>
                        </view>
                    </view>
                </view>
                
                <!-- 已检测列表 -->
                <view class="appointment-list" v-if="appointmentTab === 1">
                    <view class="appointment-item" v-for="(item, index) in completedList" :key="index">
                        <view class="flex align-center">
                            <image class="appointment-avatar" :src="item.avatar"></image>
                            <view class="margin-left-sm flex-1">
                                <view>{{item.name}}</view>
                                <view class="text-gray text-sm">检测时间：{{item.time}}</view>
                                <view class="text-gray text-sm">检测地点：{{item.center}}</view>
                                <view class="text-gray text-sm">检测师：{{item.tester}}</view>
                            </view>
                        </view>
                    </view>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
import bgImage from '@/static/tabbar/header.png'
import avatar from '@/static/tabbar/avatar.png'
export default {
    data() {
        return {
            bgImage,
            avatar,
            StatusBar: this.$statusBarHeight,
            CustomBar: this.$CustomBar,
            centers: [
                { id: 1, name: '金属世界检测中心' }
            ],
            centerIndex: 0,
            dateList: [],
            selectedDate: 0,
            timeList: [
                { time: '8:00', status: '已约满' },
                { time: '8:30', status: '已约满' },
                { time: '9:00', status: '已约满' },
                { time: '9:30', status: '已约满' },
                { time: '10:00', status: '已约满' },
                { time: '10:30', status: '余1' },
                { time: '11:00', status: '余2' },
                { time: '13:30', status: '余2' },
                { time: '14:00', status: '余2' },
                { time: '14:30', status: '余2' },
                { time: '15:00', status: '余2' },
                { time: '15:30', status: '余1' },
                { time: '16:00', status: '余2' },
                { time: '16:30', status: '余2' },
                { time: '17:00', status: '余2' },
                { time: '17:30', status: '余2' }
            ],
            selectedTime: -1,
            testers: [
                { id: 1, name: '赵先生', avatar: '/static/tabbar/avatar.png' },
                { id: 2, name: '赵先生', avatar: '/static/tabbar/avatar.png' },
                { id: 3, name: '赵先生', avatar: '/static/tabbar/avatar.png' },
                { id: 4, name: '赵先生', avatar: '/static/tabbar/avatar.png' },
                { id: 5, name: '赵先生', avatar: '/static/tabbar/avatar.png' }
            ],
            selectedTester: -1,
            appointmentTab: 0,
            myAppointments: [
                { 
                    name: '赵先生', 
                    avatar: '/static/avatar.jpg', 
                    time: '2-17 15:00', 
                    center: '金属世界检测中心', 
                    tester: '张三' 
                },
                { 
                    name: '赵先生', 
                    avatar: '/static/avatar.jpg', 
                    time: '2-17 15:00', 
                    center: '金属世界检测中心', 
                    tester: '张三' 
                }
            ],
            completedList: [],
            showScrollIndicator: false,
        };
    },
    onLoad() {
        this.generateDateList();
    },
    methods: {
        generateDateList() {
            const dateList = [];
            const weekDays = ['日', '一', '二', '三', '四', '五', '六'];
            
            for (let i = 0; i < 7; i++) {
                const date = new Date();
                date.setDate(date.getDate() + i);
                
                let dayText;
                if (i === 0) {
                    dayText = '今天';
                } else if (i === 1) {
                    dayText = '明天';
                } else if (i === 2) {
                    dayText = '后天';
                } else {
                    const month = (date.getMonth() + 1).toString().padStart(2, '0');
                    const day = date.getDate().toString().padStart(2, '0');
                    dayText = `${month}-${day}`;
                }
                
                const weekDay = weekDays[date.getDay()];
                
                dateList.push({
                    day: dayText,
                    week: `星期${weekDay}`,
                    date: date
                });
            }
            
            this.dateList = dateList;
        },
        centerChange(e) {
            this.centerIndex = e.detail.value;
        },
        selectDate(index) {
            this.selectedDate = index;
        },
        selectTime(index, time) {
            if (time.status === '已约满') return;
            this.selectedTime = index;
        },
        selectTester(index) {
            this.selectedTester = index;
        },
        confirmAppointment() {
            if (this.selectedTime === -1 || this.selectedTester === -1) {
                uni.showToast({
                    title: '请选择时间和检测师',
                    icon: 'none'
                });
                return;
            }
            
            uni.showToast({
                title: '预约成功',
                icon: 'success'
            });
        },
        calculateScrollIndicator() {
            this.$nextTick(() => {
                const query = uni.createSelectorQuery().in(this);
                // 获取所有tester-item元素
                query.selectAll('.tester-item').boundingClientRect();
                query.select('.tester-scroll').boundingClientRect();
                
                query.exec(res => {
                    if (res && res[0] && res[1]) {
                        // 计算所有tester-item的总宽度
                        let totalItemsWidth = 0;
                        if (Array.isArray(res[0])) {
                            res[0].forEach(item => {
                                totalItemsWidth += item.width;
                            });
                            // 加上padding-right的值
                            totalItemsWidth += 60; // 60rpx的padding-right
                        }
                        
                        const containerWidth = res[1].width; // 容器宽度
                        
                        console.log('内容总宽度:', totalItemsWidth, '容器宽度:', containerWidth);
                        
                        // 只有当内容总宽度大于容器宽度时才显示箭头
                        this.showScrollIndicator = totalItemsWidth > containerWidth;
                    }
                });
            });
        },
        refreshScrollIndicator() {
            setTimeout(() => {
                this.calculateScrollIndicator();
            }, 300);
        },
        onTesterScroll(e) {
            const query = uni.createSelectorQuery().in(this);
            query.selectAll('.tester-item').boundingClientRect();
            query.select('.tester-scroll').boundingClientRect();
            query.select('.tester-scroll').scrollOffset();
            
            query.exec(res => {
                if (res && res[0] && res[1] && res[2]) {
                    // 计算所有tester-item的总宽度
                    let totalItemsWidth = 0;
                    if (Array.isArray(res[0])) {
                        res[0].forEach(item => {
                            totalItemsWidth += item.width;
                        });
                        // 加上padding-right的值
                        totalItemsWidth += 60; // 考虑padding-right
                    }
                    
                    const containerWidth = res[1].width;
                    const scrollLeft = res[2].scrollLeft;
                    
                    // 如果已经滚动到接近最右侧，隐藏指示箭头
                    const maxScroll = totalItemsWidth - containerWidth;
                    console.log('当前滚动位置:', scrollLeft, '最大滚动位置:', maxScroll);
                    
                    if (scrollLeft >= maxScroll - 10) { // 添加10px的容差
                        this.showScrollIndicator = false;
                    } else {
                        this.showScrollIndicator = totalItemsWidth > containerWidth;
                    }
                }
            });
        },
    },
    mounted() {
        this.calculateScrollIndicator();
        window.addEventListener('resize', this.calculateScrollIndicator);
    },
    beforeDestroy() {
        window.removeEventListener('resize', this.calculateScrollIndicator);
    },
    watch: {
        testers: {
            handler() {
                this.$nextTick(() => {
                    this.calculateScrollIndicator();
                });
            },
            deep: true
        }
    }
};
</script>

<style>
/* 日期选择样式 */
.date-scroll-container {
    display: flex;
    padding: 10rpx 0;
}

.date-item {
    padding: 20rpx 10rpx;
    margin-right: 20rpx;
    min-width: 100rpx;
    padding-bottom: 0;
    flex-shrink: 0;
    text-align: center;
    box-sizing: border-box;
}

.date-item.selected {
    border-bottom: 4rpx solid #ff6633;
}

/* 时间选择样式 */
.time-item {
    padding: 10rpx;
    border-radius: 10rpx;
    border: 1px solid #eee;
    margin-bottom: 20rpx;
}

.time-item.disabled {
    opacity: 0.6;
}

.time-item.selected {
    background-color: #ff6633;
    color: #ffffff;
    border-color: #ff6633;
}

.time-item.selected .text-green,
.time-item.selected .text-red {
    color: #ffffff !important;
}

/* 检测师选择样式 */
.tester-scroll-container {
    position: relative;
    width: 100%;
    overflow: hidden;
}

.tester-scroll {
    width: 100%;
}

/* 改用伪元素和渐变实现右侧滑动提示效果 */
.tester-scroll-container::after {
    content: "";
    position: absolute;
    right: 0;
    top: 0;
    bottom: 0;
    width: 80rpx;
    background: linear-gradient(to right, rgba(255,255,255,0), rgba(255,255,255,0.9) 60%);
    pointer-events: none;
    z-index: 2;
}

/* 箭头指示器样式 */
.tester-scroll-indicator {
    position: absolute;
    right: 10rpx;
    top: 36%;
    transform: translateY(-50%);
    width: 40rpx;
    height: 40rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 3;
    pointer-events: none;
    transition: opacity 0.3s; /* 添加过渡效果 */
}

.tester-scroll-indicator .cuIcon-right {
    color: #CD9B62;
    font-size: 40rpx;
    font-weight: bold;
}

.tester-container {
    display: flex;
    padding-right: 60rpx; /* 增加右侧内边距，确保最后一项完全可见 */
}

.appointment-avatar-image {
    width: 80rpx;
    height: 80rpx;
    border-radius: 50%;
}

.tester-item {
    padding: 10rpx 30rpx;
    min-width: 150rpx;
    flex-shrink: 0;
    text-align: center;
}

.tester-avatar {
    width: 80rpx;
    height: 80rpx;
    border-radius: 50%;
    margin: 0 auto;
}

.tester-item.selected .tester-avatar {
    border: 3rpx solid #ff6633;
}

/* 预约列表样式 */
.appointment-tabs {
    display: flex;
    margin: 30rpx 0;
    border-bottom: 1px solid #eee;
}

.appointment-tab-item {
    position: relative;
    padding: 20rpx 30rpx;
    margin-right: 30rpx;
}

.appointment-tab-item.active {
    color: #ff6633;
    font-weight: bold;
}

.tab-line {
    position: absolute;
    bottom: -1px;
    left: 50%;
    transform: translateX(-50%);
    width: 60rpx;
    height: 4rpx;
    background-color: #ff6633;
}

.appointment-item {
    padding: 20rpx 0;
    border-bottom: 1px solid #eee;
}

.appointment-item:last-child {
    border-bottom: none;
}

.appointment-avatar {
}

/* 金色按钮样式 */
.bg-gold {
    background-color: #CD9B62;
    color: #ffffff;
}
</style> 